package cn.hdu.community.controller;

import cn.hdu.community.dto.Result;
import cn.hdu.community.service.MailService;
import cn.hdu.community.service.RedisService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.Random;

/**
 * @Author zhangxin
 * @Date 2022/4/1
 */
@RestController
@RequestMapping("/mail")
public class MailController {
    @Autowired
    MailService mailService;

    @Autowired
    HttpServletRequest httpServletRequest;

    @Autowired
    RedisService redisService;

    /**
     * 邮箱发送接口
     *
     * @param userEmail
     * @return
     */
    @RequestMapping("/sendmail")
    public Result checkCode(@RequestParam("userEmail") String userEmail) {
        String checkCode = String.valueOf(new Random().nextInt(899999) + 100000);
        String message = "【HDU社区后端开发组】您的注册验证码为：" + checkCode + "，有效时间为5分钟(若不是本人操作，可忽略该条邮件)";
        mailService.sendMail(userEmail, "注册验证码", message);
        redisService.set("checkCode" + userEmail, checkCode, "M", 5);
        return Result.success("验证码已发送", null);
    }

    @RequestMapping("/verifyCode")
    public Result verifyCode(@RequestParam("checkCode") String checkCode) {
        String check_Code = (String) redisService.get("checkCode");
        if (checkCode.equals(check_Code)) {
            return Result.success("验证成功", null);
        } else {
            return Result.error("验证失败", null);
        }
    }
}

